package com.ft.oa.security.jwt.filter;

import com.alibaba.fastjson.JSONObject;
import com.ft.oa.utils.RequestBodyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;

/**
 * 登录认证的filter，参照UsernamePasswordAuthenticationFilter，添加到这之前的过滤器
 */
@Slf4j
public class JwtAuthenticationLoginFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * 构造方法，调用父类的，设置登录地址/login，请求方式POST
     */
    public JwtAuthenticationLoginFilter() {
        super(new AntPathRequestMatcher("/login", "POST"));
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {

        String username = "";
        String password = "";
        //获取登录参数
        try(BufferedReader bufferedReader = request.getReader();) {
            String bodyStr = RequestBodyUtils.read(bufferedReader);

            JSONObject jsonObject = JSONObject.parseObject(bodyStr);
            username = jsonObject.getString("username");
            password = jsonObject.getString("password");

        }catch (Exception e){
            log.error("获取登录信息异常：{}",e.getMessage());
        }

        //封装到token中提交
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                username,password);
        return getAuthenticationManager().authenticate(authRequest);

    }
}
